<?php
class User_Model_UserMapper{
	protected $_dbTable;
	
	public function setDbTable($dbTable)
	{
		if (is_string($dbTable)) {
			$dbTable = new $dbTable();
		}
		if (!$dbTable instanceof Zend_Db_Table_Abstract) {
			throw new Exception('Invalid table data gateway provided');
		}
		$this->_dbTable = $dbTable;
		return $this;
	}
	
	public function getDbTable()
	{
		if (null === $this->_dbTable) {
			$this->setDbTable('User_Model_DbTable_User');
		}
		return $this->_dbTable;
	}
	
	public function login($username,$password,$auto=false){
		$auth=Zend_Auth::getInstance();
    	$adapter=new Zend_Auth_Adapter_DbTable(Zend_Registry::get("db_comm"));
    	$adapter->setTableName("users")
    				  ->setIdentityColumn('username')
			    	  ->setCredentialColumn('password')
			    	  ->setIdentity($username)
			    	  ->setCredential($password);
    	$result=$auth->authenticate($adapter);
    	if($result->isValid()){
    		$auth->clearIdentity();
    		$auth->getStorage()->write($adapter->getResultRowObject());
    		$authSession = new Zend_Session_Namespace('Zend_Auth');
    		$authSession->setExpirationSeconds(3600);
    		return true;
    	}else{
    		return "用户名或密码不正确";
    	}
	}
	
	public function save(User_Model_User $user)
	{		
		
		try{
			$serial=$this->getDbTable()->getAdapter()->fetchOne("select MAX(id) from users");
			if(!isset($serial)){
				$serial=0;
			}
			$serial=date("Ymd").sprintf("%04d", (int)$serial+1);
			$user->setSerial($serial);
			$result=$this->getDbTable()->insert($user->toArray());
		}catch(Exception $e){
			return Utils_SQLErrorMsg::formatException($e);
		}
		return $result;

	}
	
	private function checkUniq($serial){
		try{
			$select=$this->getDbTable()->select()->where("serial=".$serial);
			$data=$this->getDbTable()->fetchRow($select)->toArray();
		}catch(Exception $e){
			return Utils_SQLErrorMsg::formatException($e);
		}
		return count($data->toArray())>0?true:"该序列号已经存在，无法保存";
	}
	
	public function update(User_Model_User $user){
		try{
			$result=$this->getDbTable()->update($user->toArray(), "id=".$user->getId());
			return (int)$result;
		}catch(Exception $e){
			return Utils_SQLErrorMsg::formatException($e);
		}
	}
	
    public function find($id, User_Model_User $user,array $filter=null)
    {
		try{
			$user->setOptions($this->getDbTable()->find($id)->current()->toArray());
			return;
		}catch(Exception $e){
			return Utils_SQLErrorMsg::formatException($e);
		}
    }
    
    public function findAll($curPage=1,$perPage=30,$where=null){
    	if(is_null($where)){
    		$select=$this->getDbTable()->select()->order("serial DESC")->limitPage($curPage, $perPage);
    		$row=$this->getDbTable()->select();
    	}else{
    		$select=$this->getDbTable()->select()
	    		->where("name like '%".$where['keyword']."%'")
	    		->orWhere("id_card like '%".$where['keyword']."%'")
//	    		->where("sex not in ('".$where['sex']."')")
//	    		->where("finish not in ('".$where['finish']."')")
	    		->order("serial DESC")
	    		->limitPage($curPage, $perPage);
    		$row=$this->getDbTable()->select()
	    		->where("name like '%".$where['keyword']."%'")
	    		->orWhere("id_card like '%".$where['keyword']."%'");
//	    		->where("sex not in ('".$where['sex']."')")
//	    		->where("finish not in ('".$where['finish']."')");	
    	}
    	$string=$select->__toString();
    	$rows=$this->getDbTable()->fetchAll($row)->count();
		$data=array();
		try{
			$data=$this->getDbTable()->fetchAll($select)->toArray();
		}catch(Exception $e){
			return Utils_SQLErrorMsg::formatException($e);
		}
		$response=new stdClass();
		$response->page=$curPage;
		$response->total=ceil($rows/$perPage);
		$response->records=(int)$rows;
		$response->rows=$data;
		return $response;
    }
    
    public function delete($id){
    	if($id===null || $id==0){
    		return "ID不能为空";
    	}
    	$result = $this->getDbTable()->find($id);
        if (0 == count($result)) {
            return "没有找到该用户";
        }
        $result=$this->getDbTable()->update(array('actived'=>0), array("userid=? "=>$id));
        return isset($result)?true:false;
    }
    
    public function verifyEmail($email){
    	$verify=User_Model_Utils_RegExp::Email($email);
    	
    	if($verify!==true){
    		return $verify;
    	}else{
    		$where=$this->getDbTable()->getAdapter()->quoteInto('email = ?', $email);
    		$result=$this->getDbTable()->fetchRow($where);
    		if(isset($result)){
    			return "电子邮件已经注册";
    		}else{
    			return true;
    		}
    	}
    }
    
    public function verifyUsername($username){
    	$verify=User_Model_Utils_RegExp::userName($username, "ALL", 6,20);
    	if($verify!==true){
    		return $verify;
    	}else{
    		$where=$this->getDbTable()->getAdapter()->quoteInto('username = ?', $username);
    		$result=$this->getDbTable()->fetchRow($where);
    		if(isset($result)){
    			return "用户名已经被注册";
    		}else{
    			return true;
    		}
    	}
    }
    public function verifyIdentifyNumber($identifyNumber){
    	$verify=User_Model_Utils_RegExp::idCard($identifyNumber);
    	if($verify!==true){
    		return $verify;
    	}else{
    		$where=$this->getDbTable()->getAdapter()->quoteInto('identify_number = ?', $identifyNumber);
    		$result=$this->getDbTable()->fetchRow($where);
    		if(isset($result)){
    			return "身份证已经被注册";
    		}else{
    			return true;
    		}
    	}
    }
    public function verifyRegisterInfo(User_Model_User $user,$type="register"){
    	if($type==="register"){
    		$result=array(
    				"username"=>$this->verifyUsername($user->getUsername()),
    				"identify_number"=>$this->verifyIdentifyNumber($user->getIdentify_number()),
    				"password"=>User_Model_Utils_RegExp::passWord($user->getPassword(), 6,20),
    				"nickname"=>User_Model_Utils_RegExp::nickName($user->getNickname(), 4, 12)
    		);
    	}else{
    		$result=array(
    				"password"=>User_Model_Utils_RegExp::passWord($user->getPassword(), 6,20),
    				"nickname"=>User_Model_Utils_RegExp::nickName($user->getNickname(), 4, 12)
    		);
    	}

    	foreach($result as $key=>$value){
    		if($value!==true){
    			return json_encode($result);
    		}
    	}
    	return true;
    }
    
    public function findByName(String $username){
    	return $this->findByProperty("name", $username, "serial desc");
    }
    
    public function findByIdcard(String $card){
    	return $this->findByProperty("id_card",$card, "id_card desc");
    }
    
     public function findByProperty(String $propertyName, String $value,String $order,$curPage=1,$perPage=30) {
	    try {
			$select=$this->getDbTable()->select()->where($propertyName."=".$value)->order($order)
								->limitPage($curPage, $perPage);
			$rows=$this->getDbTable()->getAdapter()->fetchOne("select count(*) from users where ".$propertyName." = ".$value);
			$data=$this->getDbTable()->fetchAll($select);
			$response=new stdClass();
			$response->page=$curPage;
			$response->total=ceil($rows/$perPage);
			$response->records=(int)$rows;
			$response->rows=$data;
			return $response;
	    } catch (Exception $e) {
	      	return Utils_SQLErrorMsg::formatException($e);
	    }
	  }
    
    public function getCondition($userid,$sex){
    	$mapper=new System_Model_GaugeMapper();
    	return $mapper->findPublished($sex,$userid);
    }
    
    public function getDashboard(){
    	try{
    		$select2=$this->getDbTable()->select()->where("finish = 1");
    		$finish=$this->getDbTable()->fetchAll($select2)->count();
    		$reportMapper=new User_Model_ReportMapper();
    		$passed=$reportMapper->countPassed();
    		$questionMapper=new System_Model_QuestionMapper();
    		$count=$questionMapper->count();
    		$stdClass=new stdClass();
    		$stdClass->finish=$finish;
    		$stdClass->passed=$passed;
    		$stdClass->count=$count;
    		return $stdClass;
    	}catch(Exception $e){
    		return Utils_SQLErrorMsg::formatException($e);
    	}
    }

    

}